import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions, Image, TouchableOpacity, TextInput } from "react-native";
import { style } from '../../../../../theme/style';
import { offerStyle } from './offerStyle';
import ImagePicker from 'react-native-image-picker';
import Upload from '../../../../../utils/Upload';
import { API, API_GENERATE } from '../../../../../config/api';
import HTTP from '../../../../../utils/http';
import ModalPicDelComponent from '../../../../../component/ModalPicDelComponent';
let defaultImg = require('../../../../../imgs/addphoto.png');
let deleteIcon = require('../../../../../imgs/delete2.png');
const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;
const modalPicDelCfg = {
	visible: false,
	uri: null,
	delPress: () => { },
	picPress: () => { },
	fileId: '',
	delTextHide: true
}
export class AttachmentCpt extends Component {

	constructor(props) {
		super(props);
		this.state = {
			uriList: []
		}
		modalPicDelCfg.picPress = () => {
			modalPicDelCfg.visible = false;
			modalPicDelCfg.uri = null;
			this.setState({
				previewModalVisible: false,
			});
		}
	}

	async componentWillMount() {
		const { fileIdArry } = this.props.data;
		fileIdArry && this.getImgView(fileIdArry);
	}
	getImgView(qualificationAddress) {
		if (!qualificationAddress) return;
		qualificationAddress.map(async (fileId) => {
			await this.loadedImgs(fileId, qualificationAddress.length);
		})
	}
	async loadedImgs(fileId, length) {
		const { uriList } = this.state;
		const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
		if (response) {
			const { attachmentFileVO } = response;
			uriList.push({
				uri: response.image || '',
				type: attachmentFileVO.fileExtName.toUpperCase() || 'PNG',
				fileId,
				fileName: attachmentFileVO.segment,
				fileSize: attachmentFileVO.fileSize
			});
			if (uriList.length == length) {
				this.setState({
					uriList
				})
				this.postMessage(uriList)
			}
		}
	}
	selectPhotoTapped() {
		let imgRep = {};
		const options = {
			title: '请选择图片来源',
			cancelButtonTitle: '取消',
			takePhotoButtonTitle: '拍照',
			chooseFromLibraryButtonTitle: '相册图片',
			quality: 1.0,
			maxWidth: 500,
			maxHeight: 500,
			storageOptions: {
				skipBackup: true,
				// path: 'images'
			},
			mediaType: 'photo',
		};
		ImagePicker.showImagePicker(options, async (response) => {
			const { uriList } = this.state;
			if (response.didCancel) {
				console.log('User cancelled photo picker');
				return;
			}
			else if (response.error) {
				console.log('ImagePicker Error: ', response.error);
				return;
			}
			else if (response.customButton) {
				console.log('User tapped custom button: ', response.customButton);
				return;
			}
			else {
				imgRep.uri = response.uri;
				this.setState({
					loaded: true
				});
			}
			const uploadImgObj = {
				imgUrl: { uri: response.uri },
				url: API_GENERATE(API.IMG_UPLOAD)
			}
			let responseData = await Upload.uploadImg(uploadImgObj);
			if (responseData) {
				if (responseData.fileId) {
					imgRep.fileId = responseData.fileId;
					imgRep.type = 'PNG';
					imgRep.fileName = responseData.name
					imgRep.fileSize = responseData.fileSize
					uriList.push(imgRep);
					this.postMessage(uriList)
				}
			}
			this.setState({
				loaded: false,
				uriList
			})
		});
	}
	async postMessage(uriList) {
		let postList = []
		for (let i = 0; i < uriList.length; i++) {
			const item = uriList[i];
			postList.push({
				fileId: item.fileId,
				fileName: item.fileName,
				fileSize: item.fileSize
			})
		}
		this.props.getItemInfo(postList)
	}
	async _delete(index, fileId) {
		const { uriList } = this.state;
		if (!fileId) return;
		uriList.splice(index, 1);
		this.setState({ uriList }, () => {
			this.postMessage(uriList)
		});
	}
	enlarge(val) {
		modalPicDelCfg.visible = true;
		modalPicDelCfg.uri = val;
		this.setState({
			ls: true
		})
	}
	render() {
		let { uriList } = this.state
		let { data, propsData } = this.props || {};
		let { title } = data || {};
		return (
			<View>
				<View style={{ paddingVertical: 10 * scale, justifyContent: 'flex-start', alignItems: 'flex-start' }}>
					<View style={[offerStyle.row, offerStyle.lay || null]}>
						<Text style={styles.fontSize}>{title || '-'}</Text>
					</View>
					<View style={styles.attachmentRow}>
						{uriList && uriList.length ? uriList.map((item, i) => {
							const { uri, fileId, type } = item;
							return (
								<TouchableOpacity key={i} style={[styles.attachment, styles.uploadImgBox]}
									onPress={() => {
										if (type == 'PDF') {
											propsData.navigation.navigate('ContractPdfPage', {
												finalFileId: fileId,
												title: '附件信息'
											})
										} else {
											this.enlarge(uri)
										}
									}} activeOpacity={0.5}>
									<TouchableOpacity onPress={this._delete.bind(this, i, fileId)} style={styles.close}>
										<Image style={styles.closeImg} source={deleteIcon} />
									</TouchableOpacity>
									{
										type == 'PDF' ?
											<View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap' }}>
												<Text style={{ fontSize: 12 * scale }}>PDF文件</Text>
												<Text style={{ fontSize: 10 * scale }}>点击可查看</Text>
											</View>
											: <Image source={type == 'ERROR' ? deleteIcon : item} style={styles.covermax} />
									}

								</TouchableOpacity>
							)
						}) : null}
						<TouchableOpacity style={styles.attachmentAdd} onPress={() => {
							this.selectPhotoTapped(0);
						}} activeOpacity={0.5} >
							<Image source={defaultImg} style={styles.cover} />
						</TouchableOpacity>
					</View>
				</View>
				<ModalPicDelComponent {...modalPicDelCfg} />
			</View>
		)
	}
}

const styles = StyleSheet.create({
	circle: {
		width: 14 * scale,
		height: 14 * scale,
		borderStyle: 'solid',
		borderColor: '#0E7FFD',
		borderWidth: 1 * scale,
		borderRadius: 7 * scale,
		alignItems: 'center',
		justifyContent: 'center',
		marginRight: 6 * scale,
	},
	selectedCircle: {
		width: 6 * scale,
		height: 6 * scale,
		borderStyle: 'solid',
		borderColor: '#0E7FFD',
		borderWidth: 1 * scale,
		borderRadius: 3 * scale,
		backgroundColor: '#0E7FFD',
	},
	radioItem: {
		marginRight: 20 * scale,
		marginBottom: 10 * scale
	},
	radioBox: {
		width: 220 * scale,
	},
	timeIcon: {
		tintColor: style.color.themeColor,
		width: 17 * scale,
		height: 20 * scale,
		marginRight: 10 * scale
	},
	timeText: {
		fontSize: 13 * scale,
		color: '#333'
	},
	timeBox: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	fromTime: {
		width: 85 * scale
	},
	uploadImgBox: {
		width: 60 * scale,
		height: 60 * scale,
		marginTop: -10 * scale,
		position: 'relative'
	},
	close: {
		position: 'absolute',
		right: 6 * scale,
		top: 6 * scale,
		width: 12 * scale,
		height: 12 * scale,
		zIndex: 10,

	},
	closeImg: {
		width: 12 * scale,
		height: 12 * scale,
	},
	attachmentRow: {
		flexDirection: 'row',
		flexWrap: 'wrap',
		marginTop: 10 * scale
	},
	cover: {
		width: 60 * scale,
		height: 60 * scale,
	},
	covermax: {
		width: 49 * scale,
		height: 49 * scale,
		marginTop: 10 * scale
	},
	attachment: {
		marginBottom: 10 * scale,
	},
	attachmentAdd: {
		// width: 50 * scale,
		// height: 50 * scale,
		marginLeft: -5 * scale,
		marginTop: -5 * scale
	},
})